<template>
    <div id="Process_home"
         style="background-color: #f1f3f4; padding: 10px">
        <el-row :gutter="20">
            <el-col :span="6">
                <div class="grid-content"
                     @click="toNextPage('流程分类')">
                    <div class="icon_box">
                        <svg-icon iconClass="icon-category"></svg-icon>
                    </div>
                    <div>
                        <h3>
                            流程分类<!-- <span class="err">&nbsp;&nbsp;-10.59%</span> -->
                        </h3>
                        <p>{{ categoryTotal }}</p>
                    </div>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="grid-content"
                     @click="toNextPage('表单配置')">
                    <div class="icon_box">
                        <svg-icon iconClass="icon-form"></svg-icon>
                    </div>
                    <div>
                        <h3>表单配置<!-- <span>&nbsp;&nbsp;+15.89%</span> --></h3>
                        <p>{{ formTotal }}</p>
                    </div>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="grid-content"
                     @click="toNextPage('流程模型')">
                    <div class="icon_box">
                        <svg-icon iconClass="icon-model"></svg-icon>
                    </div>
                    <div>
                        <h3>流程模型<!-- <span>&nbsp;&nbsp;+14.15%</span> --></h3>
                        <p>{{ modelTotal }}</p>
                    </div>
                </div>
            </el-col>
            <el-col :span="6">
                <div class="grid-content"
                     @click="toNextPage('部署管理')">
                    <div class="icon_box">
                        <svg-icon iconClass="icon-deploy"></svg-icon>
                    </div>
                    <div>
                        <h3>
                            部署管理<!-- <span class="err">&nbsp;&nbsp;-10.01%</span> -->
                        </h3>
                        <p>{{ deployTotal }}</p>
                    </div>
                </div>
            </el-col>
        </el-row>
        <!-- <div class="echart_box">
      <div id="main"></div>
      <div id="main2"></div>
    </div> -->
        <div class="userList mt20">
            <el-table :data="deployList"
                      stripe
                      style="width: 100%"
                      height="calc(100vh - 250px)"
                      ref="table">
                <!-- <el-table-column
          label="流程标识"
          align="center"
          prop="processKey"
          :show-overflow-tooltip="true"
        /> -->
                <!-- 流程图 -->
                <el-dialog :title="processView.title"
                           :visible.sync="processView.open"
                           width="70%"
                           append-to-body>
                    <process-viewer :key="`designer-${processView.index}`"
                                    :xml="processView.xmlData"
                                    :style="{ height: '400px' }" />
                </el-dialog>
                <el-table-column label="流程名称"
                                 align="center"
                                 :show-overflow-tooltip="true"
                                 prop="processName"></el-table-column>
                <el-table-column label="流程分类"
                                 align="center"
                                 prop="categoryName"
                                 :formatter="categoryFormat" />
                <el-table-column label="流程版本"
                                 align="center">
                    <template slot-scope="scope">
                        <el-tag size="medium">v{{ scope.row.version }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="部署时间"
                                 align="center"
                                 prop="deploymentTime"
                                 width="180" />
                <el-table-column label="状态"
                                 align="center">
                    <template slot-scope="scope">
                        <el-tag type="success"
                                v-if="!scope.row.suspended">激活</el-tag>
                        <el-tag type="warning"
                                v-if="scope.row.suspended">挂起</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作"
                                 align="center"
                                 class-name="small-padding"
                                 width="180">
                    <template slot-scope="scope">
                        <el-button type="primary"
                                   size="mini"
                                   @click.native="handlePublish(scope.row)"
                                   v-hasPermi="['workflow:deploy:list']">版本管理</el-button>
                        <el-button type="danger"
                                   size="mini"
                                   @click="handleDelete(scope.row)"
                                   v-hasPermi="['workflow:deploy:remove']">删除</el-button>
                    </template>
                </el-table-column>

            </el-table>
        </div>
        <el-dialog title="版本管理"
                   :visible.sync="publish.open"
                   width="50%"
                   append-to-body>
            <el-table v-loading="publish.loading"
                      :data="publish.dataList">
                <el-table-column label="流程标识"
                                 align="center"
                                 prop="processKey"
                                 :show-overflow-tooltip="true" />
                <el-table-column label="流程名称"
                                 align="center"
                                 :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <el-button type="text"
                                   @click="handleProcessView(scope.row)">
                            <span>{{ scope.row.processName }}</span>
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column label="流程版本"
                                 align="center">
                    <template slot-scope="scope">
                        <el-tag size="medium">v{{ scope.row.version }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="状态"
                                 align="center">
                    <template slot-scope="scope">
                        <el-tag type="success"
                                v-if="!scope.row.suspended">激活</el-tag>
                        <el-tag type="warning"
                                v-if="scope.row.suspended">挂起</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作"
                                 align="center"
                                 class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                        <el-button type="text"
                                   size="mini"
                                   icon="el-icon-video-pause"
                                   v-if="!scope.row.suspended"
                                   @click.native="handleChangeState(scope.row, 'suspended')"
                                   v-hasPermi="['workflow:deploy:status']">挂起</el-button>
                        <el-button type="text"
                                   size="mini"
                                   icon="el-icon-video-play"
                                   v-if="scope.row.suspended"
                                   @click.native="handleChangeState(scope.row, 'active')"
                                   v-hasPermi="['workflow:deploy:status']">激活</el-button>
                        <el-button type="text"
                                   size="mini"
                                   icon="el-icon-delete"
                                   @click="handleDelete(scope.row)"
                                   v-hasPermi="['workflow:deploy:remove']">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="publishTotal > 0"
                        :total="publishTotal"
                        :page.sync="publishQueryParams.pageNum"
                        :limit.sync="publishQueryParams.pageSize"
                        @pagination="getPublishList" />
        </el-dialog>
    </div>
</template>

<script>
    import * as echarts from "echarts";
    import { listCategory } from "@/api/workflow/category";
    import {
        listDeploy,
        listPublish,
        getBpmnXml,
        changeState,
        delDeploy,
    } from "@/api/workflow/deploy";
    import { listForm } from "@/api/workflow/form";
    import {
        getProcessModelList_Api, //查询流程模型列表
    } from "@/api/workflow/model";
    import { listAllCategory } from "@/api/workflow/category"; //流程分类列表
    export default {
        data () {
            return {
                categoryTotal: 0, //流程分类总数
                formTotal: 0, //表单配置总数
                modelTotal: 0, //流程模型总数
                deployTotal: 0, //部署管理总数
                queryParams: {
                    pageNum: 1,
                    pageSize: 10,
                },
                timer: null,
                deployList: [],
                categoryOptions: [],
                processView: {
                    title: "",
                    open: false,
                    index: undefined,
                    xmlData: "",
                },
                publish: {
                    open: false,
                    loading: false,
                    dataList: [],
                },
                publishTotal: 0,
                publishQueryParams: {
                    pageNum: 1,
                    pageSize: 10,
                    processKey: "",
                },
            };
        },
        methods: {
            // 表单重置
            reset () {
                this.form = {
                    id: null,
                    processKey: null,
                    processName: null,
                    category: null,
                    state: null,
                };
                this.resetForm("form");
            },
            /** 搜索按钮操作 */
            handleQuery () {
                this.queryParams.pageNum = 1;
                this.getList();
            },
            /** 重置按钮操作 */
            resetQuery () {
                this.resetForm("queryForm");
                this.handleQuery();
            },
            // 多选框选中数据
            handleSelectionChange (selection) {
                this.ids = selection.map((item) => item.deploymentId);
                this.single = selection.length !== 1;
                this.multiple = !selection.length;
            },
            /** 查看流程图 */
            handleProcessView (row) {
                let definitionId = row.definitionId;
                this.processView.title = "流程图";
                this.processView.index = definitionId;
                // 发送请求，获取xml
                getBpmnXml(definitionId).then((response) => {
                    this.processView.xmlData = response.data;
                });
                this.processView.open = true;
            },
            getPublishList () {
                this.publish.loading = true;
                listPublish(this.publishQueryParams).then((response) => {
                    this.publish.dataList = response.rows;
                    this.publishTotal = response.total;
                    this.publish.loading = false;
                });
            },
            handlePublish (row) {
                this.publishQueryParams.processKey = row.processKey;
                this.publish.open = true;
                this.getPublishList();
            },
            /** 挂起/激活流程 */
            handleChangeState (row, state) {
                const params = {
                    definitionId: row.definitionId,
                    state: state,
                };
                changeState(params).then((res) => {
                    this.$modal.msgSuccess(res.msg);
                    this.getPublishList();
                });
            },
            handleDelete (row) {
                const deploymentIds = row.deploymentId || this.ids;
                this.$modal
                    .confirm("是否确认删除选中的数据项？")
                    .then(() => {
                        this.loading = true;
                        return delDeploy(deploymentIds);
                    })
                    .then(() => {
                        this.loading = false;
                        this.getPublishList();
                        this.getList();
                        this.$modal.msgSuccess("删除成功");
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },
            categoryFormat (row, column) {
                return (
                    this.categoryOptions.find((k) => k.code === row.category)
                        ?.categoryName ?? ""
                );
            },
            //跳转页面
            toNextPage (val) {
                if (val == "流程分类") this.$router.push("/process/business/category");
                else if (val == "表单配置") this.$router.push("/process/business/form");
                else if (val == "流程模型") this.$router.push("/process/model/model");
                else if (val == "部署管理") this.$router.push("/process/model/deploy");
            },
            //流程分类
            getCategoryTotal () {
                listCategory(this.queryParams).then((response) => {
                    this.categoryTotal = response.total;
                });
            },
            /** 流程部署 */
            getDeployTotal () {
                listDeploy(this.queryParams).then((response) => {
                    this.deployTotal = response.total;
                    this.deployList = response.rows;
                });
            },
            /** 流程表单 */
            getFormTotal () {
                listForm(this.queryParams).then((response) => {
                    this.formTotal = response.total;
                });
            },
            //流程模型
            getmodelTotal () {
                getProcessModelList_Api(this.queryParams).then((response) => {
                    this.modelTotal = response.total;
                });
            },
            //初始化
            initEchart () {
                var myChart = echarts.init(document.getElementById("main2"));
                var myChart2 = echarts.init(document.getElementById("main"));
                window.addEventListener("resize", function () {
                    myChart.resize();
                    myChart2.resize();
                });
                const option = {
                    title: {
                        text: "动态分布图",
                    },
                    xAxis: {
                        type: "category",
                        data: ["1月", "2月", "3月", "4月", "5月", "6月", "7月"],
                    },
                    yAxis: {
                        type: "value",
                    },
                    series: [
                        {
                            data: [120, 200, 150, 80, 70, 110, 130],
                            type: "bar",
                            showBackground: true,
                            backgroundStyle: {
                                color: "rgba(180, 180, 180, 0.2)",
                            },
                        },
                    ],
                };
                let base = +new Date(1968, 9, 3);
                let oneDay = 24 * 3600 * 1000;
                let date = [];
                let data = [Math.random() * 30];
                for (let i = 1; i < 20000; i++) {
                    var now = new Date((base += oneDay));
                    date.push(
                        [now.getFullYear(), now.getMonth() + 1, now.getDate()].join("/")
                    );
                    data.push(
                        Math.abs(Math.round((Math.random() - 0.5) * 20 + data[i - 1]))
                    );
                }
                const option2 = {
                    title: {
                        text: "动态分布图",
                    },
                    xAxis: {
                        show: false,
                        type: "category",
                        boundaryGap: false,
                        data: date,
                    },
                    yAxis: {
                        type: "value",
                    },
                    series: [
                        {
                            data: data,
                            type: "line",
                            areaStyle: {},
                        },
                    ],
                };
                myChart.setOption(option);
                myChart2.setOption(option2);
            },
            categoryFormat (row, column) {
                return (
                    this.categoryOptions.find((k) => k.code === row.category)
                        ?.categoryName ?? ""
                );
            },
            /** 查询流程分类列表 */
            getCategoryList () {
                listAllCategory().then(
                    (response) => (this.categoryOptions = response.data)
                );
            },
        },
        mounted () {
            // this.initEchart();
            // 拿到表格挂载后的真实DOM
            const table = this.$refs.table;
            // 拿到表格中承载数据的div元素
            const divData = table.bodyWrapper;
            // 拿到元素后，对元素进行定时增加距离顶部距离，实现滚动效果(此配置为每100毫秒移动1像素)
            this.timer = setInterval(() => {
                // 元素自增距离顶部1像素
                divData.scrollTop += 1;
                // 判断元素是否滚动到底部(可视高度+距离顶部=整个高度)
                if (divData.clientHeight + divData.scrollTop + 1 > divData.scrollHeight) {
                    // 重置table距离顶部距离
                    divData.scrollTop = 0;
                }
            }, 30); // 滚动速度
        },
        created () {
            this.getCategoryList();
            this.getCategoryTotal();
            this.getDeployTotal();
            this.getFormTotal();
            this.getmodelTotal();
        },
        beforeDestroy () {
            clearInterval(this.timer);
        },
    };
</script>

<style lang="scss" scoped>
    .app-main {
    }

    .el-row {
        margin-bottom: 20px;

        &:last-child {
            margin-bottom: 0;
        }
    }

    .el-col {
        border-radius: 4px;
    }

    .grid-content {
        border-radius: 5px;
        height: 110px;
        background-color: #ffffff;
        display: flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;
        padding: 20px 50px;

        h3 {
            // font-size: 22px;
            text-align: center;
            margin-bottom: 16px;
            white-space: nowrap;

            span {
                font-size: 14px;
                color: #6690f9;

                &.err {
                    color: #ff7270;
                }
            }
        }

        p {
            font-size: 16px;
            color: #6690f9;
            text-align: center;
        }

        .icon_box {
            width: 70px;
            height: 70px;
            margin-right: 30px;

            .svg-icon {
                width: 100%;
                height: 100%;
            }
        }
    }

    .echart_box {
        display: flex;
        justify-content: flex-start;
        box-sizing: border-box;

        #main {
            width: 50%;
            height: 300px;
            background-color: #ffffff;
            border-radius: 5px;
            padding: 10px;
            padding-bottom: 0px;
        }

        #main2 {
            width: 50%;
            margin-left: 20px;
            height: 300px;
            background-color: #ffffff;
            border-radius: 5px;
            padding: 10px;
            padding-bottom: 0px;
        }
    }
</style>